//
//  CYMyNoticeViewController.m
//  CaiYun
//
//  Created by 今日信息科技 on 2017/7/3.
//  Copyright © 2017年 今日信息科技. All rights reserved.
//

#import "CYMyNoticeViewController.h"
#import "CYDataSourceDelegate.h"
#import "CYSegmentView.h"
#import "CYMyNoticeCell.h"
#import "CYUserHeader.h"
#import "CYDiscountViewController.h"
#import "CYActivityModel.h"
#import "CYMyNoticeCellHeight.h"
@interface CYMyNoticeViewController (){
    NSUInteger page;//当前的页面
    NSUInteger total_page;//总共页面
    NSUInteger row;//请求的行数
    
}
@property (nonatomic, strong) CYSegmentView *seg;
@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) CYDelegate *delegate;
@property (nonatomic, strong) CYDataSource *datasource;
@property (nonatomic, strong) NSMutableArray *dataList;
@property (nonatomic, assign) NSUInteger currentIndex;
@end

@implementation CYMyNoticeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    page = 1;
    row = 10;
    _currentIndex =([_previousVCName isEqualToString:@"CYUserViewController"])?0:2;
    if ([_previousVCName isEqualToString:@"CYUserViewController"])
        self.seg.hidden = NO;
    // Do any additional setup after loading the view.
}
/*懒加载*/
- (CYSegmentView *)seg{
    if (!_seg) {
        
        WS(self)
        _seg = [[CYSegmentView alloc]initWithtitles:@[@"通知",@"公告",@"活动"] size:AL(PT(30)) selectColor:THEME_COLOR defaultSelectedIndex:_currentIndex block:^(NSUInteger index) {
            [weakSelf changeTrendStyle:index];
        }];
        [self.view addSubview:_seg];
        
        [_seg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsMake(NAVIBAR_HEIGHT + STATUS_HEIGHT, 0, SCREEN_HEIGHT - _seg.bounds.size.height - NAVIBAR_HEIGHT - STATUS_HEIGHT, 0));
        }];
    }
    return _seg;
}

- (UITableView *)tableview{
    if (!_tableview) {
        _tableview = [[UITableView alloc]init];
        _tableview.mj_header = [CYRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshDown)];//下拉刷新
        _tableview.mj_footer = [CYRefreshFooder footerWithRefreshingTarget:self refreshingAction:@selector(refreshUp)];//上拉加载
        [self.view addSubview:_tableview];
        [self setupTableview];
        
        [_tableview mas_makeConstraints:^(MASConstraintMaker *make) {
            if ([_previousVCName isEqualToString:@"CYUserViewController"])
                make.edges.mas_offset(UIEdgeInsetsMake(NAVIBAR_HEIGHT + STATUS_HEIGHT + _seg.bounds.size.height, 0, 0, 0));
            else
                make.edges.mas_offset(UIEdgeInsetsMake(NAVIBAR_HEIGHT + STATUS_HEIGHT, 0, 0, 0));
        }];
    }
    
    return _tableview;
}

- (NSMutableArray *)dataList{
    if (!_dataList)
        _dataList = [NSMutableArray array];
    return _dataList;
}

- (void)setupTableview{
    WS(self)
    _datasource = [[CYDataSource alloc]initWithData:_dataList identifier:@"CYMyNoticeCell" block:^(id cell, id data) {
        [weakSelf bind:cell data:data];
    }];
    
    _delegate = [[CYDelegate alloc]initWithAutoHeight:[CYMyNoticeCellHeight autoHeight:_dataList] views:nil block:^(NSIndexPath *index) {
        [weakSelf selectCell:index];
    }];
    
    _tableview.delegate = _delegate;
    _tableview.dataSource = _datasource;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    
}

/*绑定cell*/
- (void)bind:(CYMyNoticeCell *)cell data:(NSDictionary *)dict{
    cell.type = (_currentIndex == 0)?@"notice":((_currentIndex == 1)?@"public":@"activity");
    cell.title = (_currentIndex == 2)?dict[@"active_title"]:dict[@"title"];
    cell.content = (_currentIndex == 2)?dict[@"active_description"]:(_currentIndex == 1)?dict[@"content"]:dict[@"contents"];
    cell.date = (_currentIndex == 0)?dict[@"create_time"]:dict[@"time"]; //date属性赋值 放到最后,
    if (_currentIndex == 2)
        cell.imageURL = dict[@"mobile_img_url"];
}

/*选择cell的响应办法*/
- (void)selectCell:(NSIndexPath *)index{
    if (_currentIndex == 2 ){
        CYDiscountViewController *discountVC = [[CYDiscountViewController alloc]init];
        discountVC.datail_id = [_dataList[index.row][@"id"] intValue];
        [self.navigationController pushViewController:discountVC animated:YES];
    }
    
}

/*选择器*/
- (void)changeTrendStyle:(NSUInteger)index{
    _currentIndex = index;
    page = 1;
    _dataList = nil;
    [self https];
}

- (void)setupDataList:(NSMutableArray *)array{
    if (page > total_page)
        return;
    [self.dataList addObjectsFromArray:array];//则添加到datalist数组里
    self.tableview.hidden = NO;
    _datasource.dataArr = _dataList;
    _delegate.cellHeights = [CYMyNoticeCellHeight autoHeight:_dataList];
    [self.tableview reloadData];
}

/*每个cell*/
/*筛选主要文字内容，构造成数组，由此数组去自适应每个cell的高度*/
- (NSArray *)getMainText:(NSArray *)array {
    NSMutableArray *mutablArr = [NSMutableArray array];
    for (NSDictionary *dict in array) {
        if (_currentIndex == 2)
            [mutablArr addObject:dict[@"detailTitle"]];
        else
            [mutablArr addObject:dict[@"content"]];
    }
    return mutablArr;
}

//下拉刷新
- (void)refreshDown{
    _dataList = nil;
    page = 1;
    [self https];
}

//上拉加载
- (void)refreshUp{
    page++;
    [self https];
    
}

#pragma mark api
- (NSString *)getAPI{
    if (_currentIndex == 0)//通知
        return API_notice;
    else if (_currentIndex == 1)//公告
        return API_announ;
    else if (_currentIndex == 2)//活动
        return API_activity;
    return nil;
}

#pragma mark 请求体
- (NSDictionary *)getParameters{
    if (_currentIndex == 2)
        return @{@"page":@(page), @"number":@(row)};
    else
        return @{@"username":[CYCache readDataWithKey:@"username"], @"token":[CYCache readDataWithKey:@"token"], @"page":@(page), @"number":@(row)};
}

- (void)https{
    
    NSString *key = (_currentIndex == 0)?@"user_message":(_currentIndex == 1)?@"article":@"data";
  self.task = [CYHttps POST:[self getAPI] parameters:[self getParameters] showHUD:YES progress:nil success:^(id data) {
        DeLog(@"data  %@",data);
        if (_tableview){//如果tableview已经加载，结束下啦刷新动画
            [_tableview.mj_header endRefreshing];
            [_tableview.mj_footer endRefreshing];
        }
        if ([data isKindOfClass:[NSDictionary class]]){
            total_page = [data[@"total_page"] integerValue];
            [self setupDataList:data[key]];
        }
    } failure:nil];
    
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    _dataList = nil;
    [self https];
}

- (void)setupNavigationBarTintColor:(UIColor *)color{
    [super setupNavigationBarTintColor:color];
    self.navigationItem.title = ([_previousVCName isEqualToString:@"CYUserViewController"])?@"我的消息":@"优惠活动";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
